import PanelCallback from "../prefab/panel_callback";
import MsgHub from "../script/msg_hub";
import utils from "../script/utils";

const { ccclass, property } = cc._decorator;

@ccclass("PageHandle")
class PageHandle {
    @property(cc.String)
    name = "";
    @property(cc.Prefab)
    prefab: cc.Prefab = null;
};

@ccclass
export default class Game extends cc.Component {
    //页面容器
    @property(cc.Node)
    content: cc.Node = null;
    @property(cc.Node)
    boxContent: cc.Node = null;

    @property
    startPageName = "";
    @property([PageHandle])
    pages: PageHandle[] = [];
    @property([PageHandle])
    boxes: PageHandle[] = [];

    _curPage: cc.Node = null;
    get curPage() {
        return this._curPage;
    }


    _boxStack: cc.Node[] = [];

    onDestroy() {
        MsgHub.off(this);
    }

    onLoad() {
        MsgHub.on(utils.macro.EVENTS.PUSH_PAGE, this.onPushPage, this);
    }
    _getPrefab(name, list) {
        for (let i = 0; i < list.length; i++) {
            let handle = list[i];
            if (handle.name == name) {
                return handle.prefab;
            }
        }
        return null;
    }
    getPage(name) {
        return this._getPrefab(name, this.pages);
    }
    getBox(name) {
        return this._getPrefab(name, this.boxes);
    }

    onPushPage(msg) {
        // msg.name;
        // msg.handle = null;
        // msg.fade = true;
        if (!this.getPage(msg.name)) {
            cc.log("没找到页面");
            return;
        }
        if (this._curPage) {
            this._curPage.destroy();
            this._curPage = null;
        }

        var prefab = this.getPage(msg.name);
        var panel = cc.instantiate(prefab);
        this.content.addChild(panel);
        this._curPage = panel;
    }
    onPushBox(msg) {
        if (!this.getBox(msg.name)) {
            cc.log("没找到BOX");
            return;
        }
        let box = cc.instantiate(this.getBox(msg.name));
        msg.handle = box;
        box.getComponent( PanelCallback ).on( "destroy", ()=>{
            for( let i=0;i<this._boxStack.length;i++){
                if( this._boxStack[i] == box ) {
                    this._boxStack.splice(i,1);
                    break;
                }
            }
        },this);
        this.boxContent.addChild(box);
        this._boxStack.unshift(box);
    }
}
